package com.example.screenplayer;

import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;


import org.greenrobot.eventbus.EventBus;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPReceiverService extends Service {
    private static final int BROADCAST_PORT = 50001;  // 与服务端端口相同
    private static final int BROADCAST_PORT2 = 50005;  // 与服务端端口相同
    private static final String TAG = "UDPReceiverService";
    private static final String BROADCAST_ADDRESS = "255.255.255.255";  // 广播地址
    private boolean isBroadcasting = false;  // 用于标记是否正在广播

    @Override
    public void onCreate() {
        super.onCreate();
        startListening();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isBroadcasting) {
            // 启动广播线程
            startBroadcast();
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopBroadcast();

        // 停止时的清理
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void startListening() {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket(BROADCAST_PORT)) {
                socket.setBroadcast(true);  // 启用广播模式

                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                // 接收来自服务端的广播包
                while (true) {
                    socket.receive(packet);
                    String receivedMessage = new String(packet.getData(), 0, packet.getLength());

//                                Log.d(TAG, "接收到广播: " + receivedMessage);
                    InetAddress senderAddress = packet.getAddress();
                    String serverIp = senderAddress.getHostAddress();
                    // 打印接收到的广播信息、设备IP和设备型号
                    Log.d(TAG, "服务端 IP 地址: " + serverIp);
                    EventBus.getDefault().post(new ScreeIpAddress(serverIp, receivedMessage));

                    // 可以根据需求将信息发送给其他组件（如通过广播或启动 Activity 等）
                }
            } catch (Exception e) {
                Log.e(TAG, "接收广播时出错: ", e);
            }
        }).start();
    }

    private void startBroadcast() {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket()) {
                socket.setBroadcast(true);  // 启用广播模式

                String deviceModel = Build.MODEL;  // 获取设备型号

                String message = deviceModel;
                byte[] buffer = message.getBytes();

                InetAddress broadcastAddress = InetAddress.getByName(BROADCAST_ADDRESS);
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length, broadcastAddress, BROADCAST_PORT2);
                isBroadcasting = true;
                while (isBroadcasting) {
                    socket.send(packet);  // 发送广播
                    try {
                        Thread.sleep(1000);  // 每秒广播一次
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "广播发送时出错: ", e);
            }
        }).start();
    }

    private void stopBroadcast() {
        isBroadcasting = false;  // 停止广播
    }
}
